package com.minelx.serverandclient.stream;

public abstract class Indexer {
	public static final int EOF = -1;

	/**
	 * index bytes into dest.
	 *
	 * @param fromSourceAt index where we start
	 * @param dest         resulting
	 * @return how many bytes we indexed, -1 if we get to the end.
	 */
	public int indexCount(int fromSourceAt, byte[] dest) {
		if (fromSourceAt >= totalLength()) {
			return EOF;
		}
		int howMany = howManyShouldIndexed(fromSourceAt, dest.length);
		return index(fromSourceAt, howMany, dest);
	}

	private int howManyShouldIndexed(int fromSourceAt, int howMany) {
		if (fromSourceAt + howMany > totalLength())
			return totalLength() - fromSourceAt;
		return howMany;
	}

	protected abstract int index(int fromSourceAt, int howMany, byte[] dest);

	protected abstract int totalLength();
}
